var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// session依赖：
const session = require('express-session')
const MongoStore = require('connect-mongo')


const CommunityArticles = require('./routes/api/Articles')
const LoginRouter = require('./routes/api/Login')
const CommentRouter = require('./routes/api/Comments')
const NotesRouter = require('./routes/api/Notes')
const ProjectRouter = require('./routes/api/Projects')
const CategorieRouter = require('./routes/api/Categories')
var app = express();

// 应用session依赖
const { DBHOST, DBPORT, DBNAME } = require('./config/config')
// 应用session中间件
app.use(session({
  name: 'sid', //设置cookie的name，默认值：connect:sid
  secret: "SQ",//加密字符串
  saveUninitialized: false,//是否每次请求都设置一个cookie来存储session的id
  resave: true,//是否每次请求都重新保存session（如果我设置过期时间为20分钟，则每次访问都重新变成20分钟）
  store: MongoStore.create({//Mongodb保存位置
    mongoUrl: `mongodb://${DBHOST}:${DBPORT}/${DBNAME}`
  }),
  cookie: {
    httpOnly: true,//开启后无法通过js代码操作cookie
    maxAge: 1000 * 60 * 60 * 24 * 7//控制cookie过期时间
  }
}))

const cors = require('cors');
app.use(cors());
app.use(express.json()); // 解析 application/json
app.use(express.urlencoded({ extended: true })); // 解析 form 表单

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', CommunityArticles)
app.use('/api', LoginRouter)
app.use('/api', CommentRouter)
app.use('/api', NotesRouter)
app.use('/api', ProjectRouter)
app.use('/api', CategorieRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
